package csc.fresher.finalgroupfour.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.finalgroupfour.domain.State;

@Repository("stateDAO")
public class StateDAO {
	@PersistenceContext
	private EntityManager em; // Entity Manager is acquired by container.
	
	/**
	 * Add a new state.
	 * @param state
	 */
	@Transactional
	public void addState(State state) {
		em.persist(state);
	}
	
	/**
	 * List all states in DB.
	 * @return
	 */
	@Transactional
	public List<State> listStates() {
		List<State> states = new ArrayList<State>();
		TypedQuery<State> query = em.createQuery("SELECT a FROM State a", State.class);
		
		states = query.getResultList();
		if (states.size() > 0) {
			return states;
		}
		return null;
	}
	
	/**
	 * Update a state's information
	 * @param state
	 */
	@Transactional
	public void updateState(State state) {
		em.merge(state);
	}
	
	/**
	 * Remove a state from database.
	 * @param state
	 */
	@Transactional
	public void deleteState(State state) {
		em.remove(state);
	}
	
	/**
	 * Find weather a state existed or not.
	 * @param state
	 * @return
	 */
	@Transactional
	public boolean findState(State state) {
		return em.contains(state);
	}
}